<template>
  <div class="cart">
    <!-- 搜索返回 -->
    <TopBar title="购物车">
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </TopBar>
    <!-- 商品数据 -->
    <NoData :isShow="!isShow" :fontSize="26"/>
    <div class="cartShop" v-show="isShow">
      <van-swipe-cell  v-for="item,index in cartList" :key="item._id">
        <van-row type="flex" align="center">
        <van-col span="3">
          <van-checkbox v-model="item.checked" @click="checkedSelf(item)"></van-checkbox>
        </van-col>
        <van-col span="21">
            <van-card
              :num="item.num"
              :price="item.good.price"
              :desc="item.good.desc"
              :title="item.good.name"
              class="goods-card"
              :thumb="$api.baseImg + item.good.img"
            >
            <template #footer>
              <van-button size="mini" @click="changeNum(item, false)">-</van-button>
              <van-button size="mini" @click="changeNum(item, true)">+</van-button>
            </template>
            </van-card>
        </van-col>
      </van-row>
      <template #right>
        <van-button
          @click='delThisShop(item,index)'
          square
          text="删除"
          type="danger"
          class="delete-button" />
      </template>
    </van-swipe-cell>
    </div>
    <!-- 提交订单 -->
    <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit">
      <van-checkbox v-model="checkedAll">全选</van-checkbox>
      <template #tip>
        <div class="addr">
          <div class="addaddr" v-if="!addr">
            {{addr}}
            请选择地址 <a @touchend="addlist">前往选择</a>
          </div>
          <div class="primaryOfaddr" v-else>
            默认地址：<span v-text="addr"></span> <a @touchend="addlist">更换地址</a>
          </div>
        </div>
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import {NoData,TopBar} from '@/components'
export default {
name: 'Cart',
components: {
  NoData,
  TopBar
},
 data() {
   return {
     search: '',
     checked: false,
     radio: false,
     cartList: [],
     total: 0,
     isShow: true,
     addr: '',
     userInfo: {}
   }
 },
 computed: {
   checkedAll: {
     set(val) {
        this.total = 0;
       this.cartList.forEach((item) =>{
          this.$set(item, 'checked', val)
          val ? this.total += (item.num * item.good.price)*100 : this.total = 0
       })
     },
     get() {
       return (this.cartList.every(item => item.checked) && this.cartList.length)
     }
   }
   
 },
 activated() {
    this.$nextTick(() => {
      this.init()
    })
    // console.log(this.isShow);
 },
//  mounted() {
//     this.init()
//  },
 methods: {
   init() {
     this.$api.CartData().then(res => {
       this.total = 0;
       if(!res) return this.isShow = false
       this.isShow = true
       this.cartList = res || []
     })
    this.$api.userAddr().then(res => {
      if(!res) return
      res.some(item => {
        console.log(item);
        if(item.primary) {
          this.userInfo = item;
          this.addr = item.addr
        } 
      })
    })
   },
   changeNum(item,falg) {
    //  注意，逻辑，并且是数据驱动，想着怎么改数据
     if(!falg && item.num <= 1) {
       this.$dialog.alert({
         title: '警告',
         message: '商品数量不能小于1'
       })
       return
     }
     let num = falg ? ++item.num : --item.num
     const data = {
       id: item._id,
       num
     }
     this.$api.updateCart(data).then(() => {
      //  console.log(res);
       this.total = this.cartList.reduce((t,val) => {
        return val.checked ? t + (val.num * val.good.price * 100) : t
       },0)
       console.log(this.total);
     })
      // console.log(num);
   },
   checkedSelf(item) {
     item.checked ?  this.total += ( item.num * item.good.price)* 100 :  this.total -= ( item.num * item.good.price)* 100
   },
   delThisShop(item,index) {
    //  this.checkedSelf(item);
    //  console.log(item);
    item.checked ? this.total -= (item.num * item.good.price)*100 :  this.total;
    this.$api.delCartShop({id: item._id}).then(res => {
      console.log(res);
     this.cartList.splice(index,1);
    this.isShow = this.cartList.length ? true : false 
    })
   },
   onSubmit() {
     if(!this.addr) return this.$dialog.alert({
       title: '警告',
       message: '请选择收货地址'
     })
     let goods =  '';
      this.cartList.forEach(item => {
        if(item.checked) {
          goods += ';'+item._id
        }
      })
      console.log(goods);
      if(!goods)return this.$dialog.alert({
        title: '注意',
        message: '你暂未选择商品！'
      })
     const data ={
       goods,
       addr: this.addr,
       userInfo: this.userInfo,
       price: this.total/100
     }
     this.$api.buyGoods(data).then(res => {
       console.log(res);
       this.$dialog.alert({
         title: '购买成功',
         message: '消费' + (this.total / 100).toFixed(2) + '元'
       })
       if(this.cartList.length) this.cartList = []
      this.init();
     })
   },
   addaddr() {
     this.$router.push('/addaddr')
   },
   addlist() {
     this.$router.push('/addrlist')

   }
 }
}
</script>

<style lang="scss">
.cart {
  .van-nav-bar__content {
    height: 4.4rem;
  }
  .goods-card {
    margin: 0;
    background-color: white;
  }

  .delete-button {
    height: 100%;
  }
  .van-row {
    border-bottom: 1px solid #eee;
  }
  .van-nav-bar {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
  }
  .cartShop {
    margin-top: 4.4rem;
    margin-bottom: 9rem;
  }
  .goods-card {
    padding-left: 0;
  }
  .van-checkbox__icon {
    margin: auto;
  }
  
  .van-button--mini {
    width: 2rem;
    height: 2rem;
    margin-left: 0.5rem;
  }
  .primaryOfaddr {
    margin: 0 1rem;
    a {
      float: right;
    }
  }
  .addr {
    color: rgb(128, 125, 125);
    a {
      color: red;
      text-decoration: underline;
    }
  }
  
}
</style>